
from typing import List
from models.parkrecord import DbParkRecord
from database.database import Database
from models.query import ParkQuery
from utils.time import DatabaseDateTimeFormat

class ParkRecordTable(Database):

    def __init__(self):
        self.table_name = 'park_records'

    def insert(self, data : DbParkRecord):
        sql = self.get_insert_sql_from_obj(data, self.table_name)
        self.execute(sql)
        return int(self.cursor.lastrowid)

    def update(self, data : DbParkRecord): 
        sql = self.get_update_sql_from_obj(data, self.table_name)
        self.execute(sql)

    def query(self, query : ParkQuery, total : bool):
        
        args = []

        sql = f'select {"*" if not total else "count(`id`) as total"} from {self.table_name} where `erased` = 0'

        if query.user_id >= 0:
            sql += f' and `user_id` = %s'
            args.append(query.user_id)
            
        if query.task_id >= 0:
            sql += f' and `task_id` = %s'
            args.append(query.task_id)
            
        if query.date_range:
            sql += f''' and `entry_time`between "{DatabaseDateTimeFormat(query.date_range[0])}"
            and "{DatabaseDateTimeFormat(query.date_range[1])}"'''
            
        if query.search:
            sql += f''' and (`car_number` like %s or `park_name` like %s)''' 
            args.append(f'%{query.search}%')
            args.append(f'%{query.search}%')

        sql += f' order by id desc'

        if total:
            self.execute(sql, args)
            record = self.cursor.fetchone()
            return record['total']
        else:
            sql += f' limit {(query.page - 1) * query.limit},{query.limit}'
            self.execute(sql, args)
            records = self.cursor.fetchall()
            results : List[DbParkRecord] = []
            for record in records:
                results.append(DbParkRecord().load(record))
            return results
